package com.puppyrescue;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;











import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.google.android.gms.internal.bt;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.entity.ContentType;

public class AddSegnalazioneActivity extends FragmentActivity {

	int item;
	
	private static final int ACTION_TAKE_PHOTO = 2;

	//
	private static final int DIALOG_DATE = 1;
    private static final int DIALOG_TIME = 2;
    private static final int DIALOG_SPECIES = 3;
    private static final int DIALOG_BREED = 4;
    private static final int DIALOG_COLOR = 5;
    private static final int DIALOG_SIZE = 6;
    
    private Calendar dateTime;
    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MM yyyy");
    SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm");
    
    private GoogleMap mMappa;
    private Marker markerQui;
    //GEOCODER
    Geocoder geoCoder;
    //DB
    private static DataBaseManager dbManager;
    
    //VIEWs
	private ImageView imageView;
	private EditText addressText;
	private Button dateButton;
	private Button timeButton;
	private Button sendButton;
	private CheckBox checkAggressive;
	private CheckBox checkWounded;
	private CheckBox checkCollar;
	private CheckBox checkAtRisk;
	private EditText noteText;
	private EditText phoneText;
	private Button speciesButton;
	private Button breedButton;
	private Button colorButton;
	private Button sizeButton;

	private String currentPhotoPath;
	private Segnalazione segnalazione = new Segnalazione();

	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	// Album foto utilizzato dall'app 
	private String getAlbumName() {
		return getString(R.string.album_name);
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			
			storageDir = mAlbumStorageDirFactory.getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (! storageDir.mkdirs()) {
					if (! storageDir.exists()){
						Log.d(getString(R.string.app_name), "failed to create directory");
						return null;
					}
				}
			}
			
		} else {
			Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
		}
		return storageDir;
	}


	private File setUpPhotoFile() throws IOException {
		
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
		
		segnalazione.setPhotoPath(imageF.toString());
		currentPhotoPath = imageF.getAbsolutePath();
		
		return imageF;
	}

	private void setPic() {

		// Grandezza della ImageView 
		int targetW = imageView.getWidth();
		int targetH = imageView.getHeight();
		// Grandezza dell'immagine 
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
		segnalazione.setPhotoFile( new File(currentPhotoPath));
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;
		
		if ((targetW > 0) && (targetH > 0)) {
			Math.min(photoW/targetW, photoH/targetH);	
		}
		bmOptions.inJustDecodeBounds = false;
		//bmOptions.inSampleSize = scaleFactor;
		bmOptions.inSampleSize = 4;
		bmOptions.inPurgeable = true;

		//Decode the JPEG file into a Bitmap 
		Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
		
		// Associo la Bitmap alla ImageView 
		imageView.setImageBitmap(bitmap);
		
		segnalazione.setFoto(bitmap);
	}

	private void galleryAddPic() {
			
		    Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
			File f = new File(currentPhotoPath);
		    Uri contentUri = Uri.fromFile(f);
		    mediaScanIntent.setData(contentUri);
		    this.sendBroadcast(mediaScanIntent);
	}

	private void dispatchTakePictureIntent(int actionCode) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

			File f = null;
			
			try {
				f = setUpPhotoFile();
				currentPhotoPath = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
				
			} catch (IOException e) {
				e.printStackTrace();
				f = null;
				currentPhotoPath = null;
			}
			
		startActivityForResult(takePictureIntent, actionCode);
	}
	
	private void handleCameraPhoto() {
			setPic();
			galleryAddPic();

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_segnalazione);
		//
		dbManager = new DataBaseManager(this);
		//
		imageView = (ImageView) findViewById(R.id.photoView);
		addressText = (EditText) findViewById(R.id.addressText);
		noteText = (EditText) findViewById(R.id.noteText);
		phoneText = (EditText) findViewById(R.id.phoneNumber);
		checkAggressive = (CheckBox ) findViewById(R.id.check_aggressive);
		checkAtRisk = (CheckBox) findViewById(R.id.check_at_risk);
		checkCollar = (CheckBox) findViewById(R.id.check_collar);
		checkWounded = (CheckBox) findViewById(R.id.check_wounded);
		dateButton = (Button) findViewById(R.id.pick_date);
		timeButton = (Button) findViewById(R.id.pick_time);
		speciesButton = (Button) findViewById(R.id.btnSpecies);
		breedButton = (Button) findViewById(R.id.btnBreed);
		colorButton = (Button) findViewById(R.id.btnColor);
		sizeButton = (Button) findViewById(R.id.btnSize);
		sendButton = (Button) findViewById(R.id.buttonInvia);
		
		//LISTENER SUL BOTTONE SPECIE
		speciesButton.setText("Specie");
		speciesButton.setOnClickListener(
				  new Button.OnClickListener() {
					@Override
					public void onClick(View v) {
						showDialog(DIALOG_SPECIES);						
					}
					
		});
		
		//LISTENER SUL BOTTONE Razza
				breedButton.setText("Razza");
				breedButton.setOnClickListener(
						  new Button.OnClickListener() {
							@Override
							public void onClick(View v) {
								showDialog(DIALOG_BREED);						
							}
							
		});	
				
		//LISTENER SUL BOTTONE COLORE
		colorButton.setText("Colore");
		colorButton.setOnClickListener(
				  new Button.OnClickListener() {
					@Override
					public void onClick(View v) {
						showDialog(DIALOG_COLOR);						
							}
							
		});
		
		//LISTENER SUL BOTTONE Taglia
		sizeButton.setText("Taglia");
		sizeButton.setOnClickListener(
				  new Button.OnClickListener() {
					@Override
					public void onClick(View v) {
						showDialog(DIALOG_SIZE);						
					}
					
		});	
		//LISTENER PER SCATTARE LA FOTO
		imageView.setOnClickListener(new ImageView.OnClickListener() {
			@Override
			public void onClick(View v) {
				dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
			}
		});
		
		// LISTENER SUL BOTTONE DATA
		dateButton.setOnClickListener(
				new Button.OnClickListener() {
					@Override
					public void onClick(View v) {
						showDialog(DIALOG_DATE);						
					}
		});
		// LISTENER SUL BOTTONE ORA
		timeButton.setOnClickListener(
				new Button.OnClickListener() {
			
					@Override
					public void onClick(View v) {
						showDialog(DIALOG_TIME);					
					}
		});
		//DATA ATTUALE
		dateTime = Calendar.getInstance();

	    dateButton.setText(dateFormatter.format(dateTime.getTime()));
	    timeButton.setText(timeFormatter.format(dateTime.getTime()));
	    
	    segnalazione.setDateHour(dateTime.getTime());
	    // CONTROLLA LA VERSIONE DI ANDROID PER LA POSIZIONE DELL'ALBUM 
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
			mAlbumStorageDirFactory = new FroyoAlbumDirFactory();
		} else {
			mAlbumStorageDirFactory = new BaseAlbumDirFactory();
		}
		// MAPPA
		mMappa = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

		geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
		//MANAGER GPS 
		GpsManager gps = new GpsManager(this);
		//SE E' PRESENTE UNA POSIZIONE GEOGRAFICA
		if(gps.canGetLocation()){
            //LEGGO LATITUDINE E LONGITUDINE
            double latitudine = gps.getLatitude();
            double longitudine = gps.getLongitude();
            //
            segnalazione.setLatitude(latitudine);
            segnalazione.setLongitude(longitudine);
            
            LatLng latLong = new LatLng(latitudine, longitudine);
                      
            markerQui = mMappa.addMarker(new MarkerOptions().
            		position(latLong).title(getString(R.string.placeLabel)));      
            
            //Geocoding inverso
            try {
	            List<Address> addresses = geoCoder.getFromLocation(latitudine,longitudine, 1);
	            
	            String strCompleteAddress= "";
	            String strAddressCity= addresses.get(0).getLocality();
	            if (addresses.size() > 0){
	            for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
	            	strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
	            }
	            addressText.setText(strCompleteAddress);
	            segnalazione.setPlace(strCompleteAddress);
	            segnalazione.setCity(strAddressCity);
            }
            catch (IOException e) {
            	e.printStackTrace();
            }
            centerOnMarker(latLong);
        }
		else{
            // Mostra le impostazioni accesso alla posizione
            gps.showSettingsAlert();
        }
		//LISTENER FINE SCRITTURA
		addressText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
  
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
								
				try {
					List<Address> addresses = geoCoder.getFromLocationName(v.getText().toString(), 1);
					if (addresses.size() > 0){
						String strCompleteAddress= "";
			            for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++){
			            	strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
			            	
			            }
			            segnalazione.setCity(addresses.get(0).getLocality());
			            LatLng latLong = new LatLng(addresses.get(0).getLatitude(), addresses.get(0).getLongitude());
		            	addressText.setText(strCompleteAddress);
		            	
		            	markerQui.setPosition(latLong);
		            	centerOnMarker(latLong);
			            }
				} catch (IOException e) {
					e.printStackTrace();
				}
				segnalazione.setPlace(addressText.getText().toString());
				return false;
			}
		});
		noteText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				segnalazione.setNote(s.toString());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		phoneText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				segnalazione.setTelephone(s.toString());
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
		//LISTENER PER IL BOTTONE INVIA
		sendButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				segnalazione.setAggressive(checkAggressive.isChecked());
				segnalazione.setAtRisk(checkAtRisk.isChecked());
				segnalazione.setCollar(checkCollar.isChecked());
				segnalazione.setWounded(checkWounded.isChecked());
				//CREO UN TASK PER L'INVIO IN BACKGROUND
				AddSegnalazioneTask addTask = new AddSegnalazioneTask();
				addTask.setContext(AddSegnalazioneActivity.this);
				//MANDO IN ESECUZIONE IL TASK
				addTask.execute();
			}
		});
		
		
		
	}
	
	
	
	// CENTRA E ZOOMA LA MAPPA SUL NUOVO PUNTO 
	private void centerOnMarker(LatLng latLong ) {
		
		 mMappa.moveCamera(CameraUpdateFactory.newLatLng(latLong));
         // Zoom
         mMappa.animateCamera(CameraUpdateFactory.zoomTo(15));
         markerQui.setSnippet(addressText.getText().toString());
         markerQui.showInfoWindow();
	}
	
	//CLASSE DIALOG PER SELEZIONARE  DATA E ORA
	protected Dialog onCreateDialog(int id)
	
	{
	   
	   AlertDialog.Builder builder = new AlertDialog.Builder(this);
	   switch (id)
	   {
	   case DIALOG_DATE:
	       return new DatePickerDialog(this, new OnDateSetListener()
	       {
	
	           @Override
	           public void onDateSet(DatePicker view, int year,
	                   int monthOfYear, int dayOfMonth)
	           {
	               dateTime.set(year, monthOfYear, dayOfMonth);
	               dateButton.setText(dateFormatter.format(dateTime.getTime()));
	        	   segnalazione.setDateHour(dateTime.getTime());
	           }
	       }, dateTime.get(Calendar.YEAR),
	          dateTime.get(Calendar.MONTH),
	          dateTime.get(Calendar.DAY_OF_MONTH));
	
	   case DIALOG_TIME:
	       return new TimePickerDialog(this, new OnTimeSetListener()
	       {
	
	           @Override
	           public void onTimeSet(TimePicker view, int hourOfDay,
	                   int minute)
	           {
	               dateTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
	               dateTime.set(Calendar.MINUTE, minute);
	               timeButton.setText(timeFormatter.format(dateTime.getTime()));
	        	   segnalazione.setDateHour(dateTime.getTime());
	           }
	       }, dateTime.get(Calendar.HOUR_OF_DAY),
	          dateTime.get(Calendar.MINUTE), true);
	       
	   case DIALOG_SPECIES:
	    builder.setTitle(R.string.puppyDesc)
        .setItems(R.array.species, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            // The 'which' argument contains the index position
            // of the selected item
            	item = which;
            	String [] speciesArray;
            	speciesArray = getResources().getStringArray(R.array.species);
            	speciesButton.setText(speciesArray[which]);
            	segnalazione.setSpecies(speciesArray[which]);
            }
        });
	    return builder.create();
	   
	   case DIALOG_BREED:
		if(item == 0){
		builder.setTitle(R.string.puppyDesc)
	    .setItems(R.array.dogbreed, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        // The 'which' argument contains the index position
	        // of the selected item
	            	String [] breedArray;
	            	breedArray = getResources().getStringArray(R.array.dogbreed);
	            	breedButton.setText(breedArray[which]);
	            	segnalazione.setBreed(breedArray[which]);
	        }
	    });
		return builder.create();
	   }
		else if(item == 1){
			builder.setTitle(R.string.puppyDesc)
		    .setItems(R.array.catbreed, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) {
		        // The 'which' argument contains the index position
		        // of the selected item
		            	String [] breedArray;
		            	breedArray = getResources().getStringArray(R.array.catbreed);
		            	breedButton.setText(breedArray[which]);
		            	segnalazione.setBreed(breedArray[which]);
		        }
		    });
			return builder.create();
		}
	   case DIALOG_COLOR:
			builder.setTitle(R.string.puppyDesc)
		    .setItems(R.array.color, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) {
		        // The 'which' argument contains the index position
		        // of the selected item
		        	String [] colorArray;
	            	colorArray = getResources().getStringArray(R.array.color);
	            	colorButton.setText(colorArray[which]);
	            	segnalazione.setColor(colorArray[which]);
		        }
		    });
			return builder.create();
	   case DIALOG_SIZE:
			builder.setTitle(R.string.puppyDesc)
		    .setItems(R.array.size, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) {
		        // The 'which' argument contains the index position
		        // of the selected item
		        	String [] sizeArray;
	            	sizeArray = getResources().getStringArray(R.array.size);
	            	sizeButton.setText(sizeArray[which]);
	            	segnalazione.setSize(sizeArray[which]);
		        }
		    });
			return builder.create();	
	
	   }
	   
	   return null;
	}

	//GESTIAMO IL RITORNO DALLA INTENT PER LA FOTOCAMERA
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
				
		if (resultCode == RESULT_OK) {
			handleCameraPhoto();
		}
	}

	//INVIO DELLA SEGNALAZIONE E LETTURA DELLA RISPOSTA
	public boolean postSegnalazione() {
    	
    	String apiURL = getString(R.string.apiURL);
    	
    	String readFeed = readJSON(apiURL);
    	try{
    		JSONObject jsonObject=new JSONObject(readFeed);
    	
    		if(jsonObject.getString("esito").equals("ok"))
    			{
    			return true;
    			}
    		else{
    			
    			return false;
    		}
    		
    	}
    	catch(Exception e) {
    		e.printStackTrace();
    		
	     	return false;
    	}
    }
	//INVIO DELLA SEGNALAZIONE E LETTURA DELLA RISPOSTA
	public String readJSON(String URL) {
    	StringBuilder builder = new StringBuilder();
    	HttpClient client = new DefaultHttpClient();
    	// UTILIZZIAMO POST
    	HttpPost httpPost = new HttpPost(URL);
    	
    	try {
    	            
	    	MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

           
            multipartEntity.addPart("date_hour",new StringBody(segnalazione.getDateHour(), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("latitude",new StringBody(segnalazione.getLatitude(),ContentType.TEXT_PLAIN));
            multipartEntity.addPart("longitude",new StringBody(segnalazione.getLongitude(),ContentType.TEXT_PLAIN));
            if (segnalazione.hasPhoto()) {
            	multipartEntity.addPart("photo", new FileBody(segnalazione.getPhotoFile()));
            }
            
            multipartEntity.addPart("place",new StringBody(segnalazione.getPlace(), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("is_aggressive", new StringBody(String.valueOf(segnalazione.isAggressive()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("is_wounded", new StringBody(String.valueOf(segnalazione.isWounded()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("is_at_risk", new StringBody(String.valueOf(segnalazione.isAtRisk()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("has_collar", new StringBody(String.valueOf(segnalazione.hasCollar()), ContentType.TEXT_PLAIN));
            
            multipartEntity.addPart("species", new StringBody(String.valueOf(segnalazione.getSpecies()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("breed", new StringBody(String.valueOf(segnalazione.getBreed()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("color", new StringBody(String.valueOf(segnalazione.getColor()), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("size", new StringBody(String.valueOf(segnalazione.getSize()), ContentType.TEXT_PLAIN));
            Log.d(getString(R.string.app_name), "stringa in utf:"+segnalazione.getNoteUTF());
            multipartEntity.addPart("note", new StringBody(segnalazione.getNoteUTF(), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("telephone", new StringBody(segnalazione.getTelephone(), ContentType.TEXT_PLAIN));
            multipartEntity.addPart("city",new StringBody(segnalazione.getCity(), ContentType.TEXT_PLAIN));
            
            httpPost.setEntity(multipartEntity.build());
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
	    	int statusCode = statusLine.getStatusCode();
	    	
	    	if (statusCode == 200) {
		    	HttpEntity entity = response.getEntity();
		    	InputStream content = entity.getContent();
		    	BufferedReader reader = new BufferedReader(new InputStreamReader(content));
		    	String line;
		    	while ((line = reader.readLine()) != null) {
		    		builder.append(line);
		    	}
	    	} else {
	    		Log.e( this.toString(), "Failed to send. ERROR CODE: "+statusCode);
	    	}
    	} catch (ClientProtocolException e) {
    		e.printStackTrace();
    	} catch (IOException e) {
    		e.printStackTrace();
    	}
    	
    	return builder.toString();
    }
		//TASK ASINCRONO PER LA CONSUMAZIONE DELL'API REST
		public class AddSegnalazioneTask extends AsyncTask<Void, Integer, Integer>{
			 protected Integer status;
		     protected Context appContext;
		     protected ProgressDialog progressDialog;
		     
		     
		     protected void setContext(Context c){
		    	 this.appContext = c;
		     }
		     @Override
		     protected void onPreExecute() {
		         this.progressDialog = ProgressDialog.show(appContext, 
		        		 getText(R.string.sending_title),getText(R.string.sending));
	
		     }
			@Override
			protected Integer doInBackground(Void... params) {
				if (Utils.isConnected(appContext)){
		               if (!postSegnalazione()) {            	
		            	   dbManager.addSegnalazione(segnalazione);
		            	   // INVIO AL SERVER FALLITO
		            	   return -1; 
		                } else {
		                	//INVIO RIUSCITO
		                    return 0;
		                }
		            } else {
		            	dbManager.addSegnalazione(segnalazione);
		            	return 1; 
		            }
			}
		   @Override
	        protected void onPostExecute(Integer result) {
	            progressDialog.cancel();
	            //CONTROLLA IL RISULTATO DELL'INVIO
	            if (result == 1) {
	                Utils.showToast(appContext, R.string.added_offline);
	            } else if (result == -1) {
	
	                Utils.showToast(appContext, R.string.added_failed);
	            } else if (result == 0) {
	                
	                Utils.showToast(appContext, R.string.added_online);
	            }
	
		        }
	
		}


}